import json
from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import userInfo,userGroup
# Create your views here.

from .utils.user_expiration  import userValidity

def auth_user(func):
    def _inner(request):
        if  request.session.get('is_login',None) == None:
            return redirect('/')
        return func(request)
    return _inner

def login(request):
    if request.method == 'GET':
        if request.session.get('is_login',None):
            return redirect('/users/')  # 交给处理函数index
            #return HttpResponseRedirect(reverse('users'))
        else:
            return render(request,'pages-login.html')
    else:
        ret = {'error':'','login':False,'username':''}
        inputUser = request.POST.get('username').strip()
        inputPwd = request.POST.get('password').strip()
        rememberTime=request.POST.get('rememberTime',0)
        obj = userInfo.objects.filter(userName=inputUser)
        if inputUser == '' or inputPwd == '':
            ret['error'] = '用户名密码不能为空'
        elif len(obj) == 0:
            ret['error'] = '用户名不存在'
        elif obj[0].userPassword != inputPwd :
            ret['error'] = '密码错误'
        else:
            ret['login'] = True
            loginUserObj = userInfo.objects.get(userName=inputUser)
            request.session['username']=inputUser
            request.session['user_id']=loginUserObj.uid
            request.session['user_email']=loginUserObj.userEmail
            request.session['user_humanName']=loginUserObj.userNameHuman
            request.session['is_login']=True
            request.session.set_expiry(int(rememberTime)*24*3600)
        ret['username']=inputUser
        return HttpResponse(json.dumps(ret))
def logout(request):
    request.session.clear()
    return redirect('/')

@auth_user
def userservice(request):
    if request.method == 'GET':
        allUser = userInfo.objects.all()
        allGroups = userGroup.objects.all()
        return render(request,'pages-users.html',{'allUser':allUser,'allGroups':allGroups})
    else:
        flag = request.POST.get('flag',None)
        if flag == 'chengeActive':
            uid = request.POST.get('uid',None)
            active = request.POST.get('active',None)
            userObj = userInfo.objects.get(uid=uid)
            userObj.userIsActive = active
            userObj.save()
            if int(active) == 1:  # 如果用户被停用，清除session
                request.session.clear()
            return HttpResponse('ok')
        elif flag =='del':
            useridlist = request.POST.getlist('useridlist[]')
            for i in range(len(useridlist)):
                userdelobj = userInfo.objects.get(uid=useridlist[i])
                userdelobj.delete()
                owergroupid = userdelobj.usergroup_id
                owergroupobj = userGroup.objects.get(gid=owergroupid)
                owergroupobj.usersNum -=1
                owergroupobj.save()
            return HttpResponse('ok')

        else:
            usernameHuman = request.POST.get('usernameHuman',None)
            username = request.POST.get('username',None)
            password = request.POST.get('password',None)
            email = request.POST.get('email',None)
            usertype = request.POST.get('usertype',None)
            usergroup = request.POST.get('usergroup',None)
            active = request.POST.get('active',None)
            expiration = request.POST.get('expiration',None)
            obj = userInfo.objects.get_or_create(
                userName=username,
                userNameHuman=usernameHuman,
                userEmail=email,
                userPassword=password,
                userType=int(usertype),
                userValidity=userValidity(expiration),
                userIsActive=int(active),
                usergroup_id=int(usergroup),
                )
            userobj, status = obj
            if status == True:
                groupObj = userGroup.objects.get(gid=usergroup)
                groupObj.usersNum +=1
                groupObj.save()
            return HttpResponse(status)
@auth_user
def index(request):
    #用户登录后的首页，已经有session，可以根据session获取用户名
    #根据用户名来获取用户权限，头像等等信息，然后定制渲染页面。
    return render(request,'index.html')
@auth_user
def groupservice(request):
    if request.method == 'GET':
        allgroups = userGroup.objects.all()
        return render(request,'pages-groups.html',{'allgroups':allgroups})
    else:
        flag = request.POST.get('flag',None)
        gid = request.POST.get('id', None)
        groupname = request.POST.get('groupname', None)
        groupdes = request.POST.get('groupdes', None)
        if flag == 'add':
            if groupname == None or groupdes == None:
                message = {'msg': False}
                return HttpResponse(json.dumps(message))
            else:
                obj = userGroup.objects.get_or_create(userGroupName=groupname,userGroupDes=groupdes)
                usernum,status = obj
                newGroupObj = userGroup.objects.get(userGroupName=groupname)
                newGroupGid = newGroupObj.gid
                message = {'msg':status,'usernum':usernum.usersNum,'gid':newGroupGid}
                return HttpResponse(json.dumps(message))
        elif flag == 'del':
            #todo:如果组中还有用户不能删除。
            userGroup.objects.get(gid=gid).delete()
            return HttpResponse('ok')
        elif flag == 'edit':
            obj = userGroup.objects.get(gid=gid)
            obj.userGroupName = groupname
            obj.userGroupDes = groupdes
            obj.save()
            return HttpResponse('ok')
@auth_user
def test(request):
    a = ['tin','2q3e','jli','oasd']
    return render(request,'test.html',{'testlog':'数据堂','a':a})